//
//  CWUserAccountViewModel.swift
//  CWWeibo06
//
//  Created by ycw on 2017/7/25.
//  Copyright © 2017年 xiaowei. All rights reserved.
//

import UIKit

class CWUserAccountViewModel: NSObject {
    
    //设计成单例模式以便于数据共享
    static let userAccountViewModel: CWUserAccountViewModel = CWUserAccountViewModel()
    
    //用户模型
    var userModel: CWUserAccount?
    
    private override init() {
        super.init()
        //代码执行到此说明对象已经创建完成
        userModel = CWUserAccount.readUserAccount()
    }
    var accessToken: String? {
        
        guard let token = userModel?.access_token else {
            return nil
        }
        if userModel?.expires_date?.compare(Date()) == .orderedDescending {
            
            //token没有过期
            return token
        }else{
            return nil
        }
    }
    
    //判断用户是否登录
    var isLogin: Bool {
        
        return accessToken != nil
    }
    
    
    //MARK: 获取用户信息
    open func requestUserInfo(accountModel: CWUserAccount,callBack: @escaping (Bool)->()) {
        
        CWNetworkTool.sharedTools.requestUserInfo(access_token: accountModel.access_token!, uid: accountModel.uid) { (responseObject, error) in
            
            if error != nil{
                callBack(false)
                //print(error!)
                return
            }else{
                
                let dict = responseObject as! [String: Any]
                
                accountModel.name = dict["name"] as! String?
                
                accountModel.avatar_large = dict["avatar_large"] as! String?
                
                accountModel.saveUserAccount()
                
                //为模型赋值
                self.userModel = accountModel
                callBack(true)
            }
            
        }
        
    }

}
